package com.example.jf.jfapp;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.jf.jfapp.activity.base.BaseActivity;

import com.example.jf.jfapp.adapter.UpImageAdapter;
import com.example.jf.jfapp.bean.ChooseImageBean;
import com.example.jf.jfapp.bean.LoginResponse;
import com.example.jf.jfapp.bean.base.PublishActivityPermissionsDispatcher;
import com.example.jf.jfapp.bean.request.SendStatuRequest;
import com.example.jf.jfapp.utils.AppConfigUtils;
import com.example.jf.jfapp.utils.Constant;
import com.example.jf.jfapp.utils.RequestUtils;
import com.example.jf.jfapp.utils.UpFileUtils;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;

import static com.example.jf.jfapp.bean.ChooseImageBean.TYPE_ADD;
import static com.example.jf.jfapp.bean.ChooseImageBean.TYPE_IMAGE;

public class PublishActivity extends BaseActivity {

    //返回结果码
    public final static int STATU_SEND_RESULT_CODE = 222;

    //返回数据的key
    public final static String STATU_SEND_RESULT_KEY = "STATU_SEND_RESULT_KEY";

    //启动相册请求码
    public static final int START_PICK_CODE = 0;


    @BindView(R.id.statusHeight)
    ImageView statusHeight;
    @BindView(R.id.tv_cancle)
    AppCompatTextView tvCancle;
    @BindView(R.id.sendStatu)
    AppCompatTextView sendStatu;
    @BindView(R.id.editText)
    AppCompatEditText editText;
    @BindView(R.id.imageAction)
    AppCompatImageView imageAction;
    @BindView(R.id.up_iv)
    RecyclerView up_iv;
    ArrayList<ChooseImageBean> mChooseImageBeens = new ArrayList<>();

    //ArrayList<Uri> mUris = new ArrayList<>();
    private UpImageAdapter mUpImageAdapter;

    //选择图片的Uri，如果有选过图片，那么不为空
//    Uri mImageUri;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);
        ButterKnife.bind(this);
        initView();
    }
    @Override
    public void initView() {
        ButterKnife.bind(this);
        PublishActivityPermissionsDispatcher.showCameraWithCheck(this);

        // 添加+号的数据
        mChooseImageBeens.add(new ChooseImageBean(TYPE_ADD,null));

        //F2 跳转下一个错误





//        UpImageAdapter
        up_iv.setLayoutManager(new GridLayoutManager(this,4));
        mUpImageAdapter = new UpImageAdapter(mChooseImageBeens);
        up_iv.setAdapter(mUpImageAdapter);

    }

    @OnClick({R.id.tv_cancle, R.id.sendStatu, R.id.imageAction})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancle:
                finish();
                break;
            case R.id.sendStatu:
                sendStatu();
                break;
            case R.id.imageAction:
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, START_PICK_CODE);
                break;

        }
    }
    /**
     * 此方法会判断输入内容和图片是否为空
     * 执行上传图片操作，上传完毕直接调用sendStatu()方法，将文本内容和图片链接发布出去
     */
    public void sendStatu() {
        //内容
        String content = editText.getText().toString();

        //预先判断
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(this, "动态文本不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mChooseImageBeens.isEmpty()) {
            Toast.makeText(this, "图片不能为空", Toast.LENGTH_SHORT).show();
            return;
        }


        //先构造上传的参数
        SendStatuRequest sendStatuRequest = new SendStatuRequest();
        LoginResponse loginResponse = AppConfigUtils.getInstance().getLoginInfo(this);
        sendStatuRequest.setUserId(loginResponse.getObjectId());
        sendStatuRequest.setContent(content);

        //先上传图片
        upFile(sendStatuRequest);

    }

    /**
     * 上传图片
     * @param sendStatuRequest  预先构造的请求参数
     */
    public void upFile(final SendStatuRequest sendStatuRequest) {
        showProgressDialog("发布中...");


        //挑选数据，将图片数据挑出来
        ArrayList<Uri> mUris = new ArrayList<>();
        for (int i = 0; i < mChooseImageBeens.size(); i++) {
            if(mChooseImageBeens.get(i).getType() == TYPE_IMAGE) {
                mUris.add(mChooseImageBeens.get(i).getUri());
            }
        }


        final UpFileUtils upFileUtils = new UpFileUtils(this,mUris);
        upFileUtils.start(new UpFileUtils.UpStateListener() {
            @Override
            public void onSucceed(ArrayList<String> successImages) {
                Log.e(TAG, "onSucceed: 成功了"+ successImages.toString());



                sendStatuRequest.setImageUrls(successImages);

                //真正发布动态
                sendStatu(sendStatuRequest);



            }

            @Override
            public void onProgrees(int index) {
                showProgressDialog("正在上传第" + index +"图片");
            }

            @Override
            public void onFailure(final int index) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(PublishActivity.this);
                        builder.setTitle("提示！！！");
                        builder.setMessage("上传第"+index+"失败，是否重试？");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                upFileUtils.retry();
                            }
                        });
                        builder.show();
                    }
                });
            }

        });

    }

    /**
     * 发布动态
     * @param sendStatuRequest
     */
    public void   sendStatu(SendStatuRequest sendStatuRequest) {
        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = RequestUtils.requestPOST(sendStatuRequest,Constant.URL.SHARESTATU);
//            Request request=new Request.Builder()
//                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
//                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
//                .addHeader("Content-Type", "application/json")
//                .url(Constant.URL.SHARESTATU)
//                .get()
//                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        showToast("发布失败");

                        return;
                    }
                });

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                    }
                });

                if (response.code() == 200) {
                    String result = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast("发布中");
                        }
                    });
String userId=AppConfigUtils.getInstance().getLoginInfo(PublishActivity.this).getObjectId();
                    if ("".equals(userId)){
                        Intent intent=new Intent(PublishActivity.this,LoginActivity.class);
                        startActivity(intent);


                    }
                    Log.e(TAG, "onResponse: " + result);
                    Intent intent = new Intent();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PublishActivity.this,"发布成功",Toast.LENGTH_SHORT).show();
                        }
                    });

                    intent.putExtra(STATU_SEND_RESULT_KEY, true);
                    setResult(STATU_SEND_RESULT_CODE, intent);
                    finish();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast("发布失败。");
                            Log.e(TAG, "run: "+response.code() );
                        }
                    });
                }

            }
        });
    }

    /**
     * 根据对应的Uri 获取真实的文件路径
     * @param context
     * @param uri
     * @return
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    //监听相册返回的图片Uri
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == START_PICK_CODE) {
                Uri uri = data.getData();
//                up_iv.setVisibility(View.VISIBLE);
//                Glide.with(StatusSendActivity.this)
//                        .load(uri)
//                        .diskCacheStrategy(DiskCacheStrategy.ALL)
//                        .into(up_iv);
//                mImageUri = uri;

                //mUris.add(uri);
                //将图片封装为对象

                mChooseImageBeens.add(mChooseImageBeens.size()-1,new ChooseImageBean(TYPE_IMAGE,uri));
                if(mChooseImageBeens.size() == 4){
                    //删除+号数据
                    mChooseImageBeens.remove(mChooseImageBeens.size() - 1);
                }
                mUpImageAdapter.notifyDataSetChanged();
            }
        }
    }



    //权限--------------------------------------------------------
    @NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
    public void showCamera() {
        Log.e(TAG, "showCamera: ");
    }

    /**
     * 显示理由
     *
     * @param request
     */
    @OnShowRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
    public void showRationaleForCamera(PublishActivityPermissionsDispatcher.ShowCameraPermissionRequest request) {
        Log.e(TAG, "showRationaleForCamera: ");
        showRationaleDialog(request);
    }

    private void showRationaleDialog(final PublishActivityPermissionsDispatcher.PermissionRequest request) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("没有权限无法发动态，是否授权？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                request.cancel();
                finish();
            }
        });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                request.proceed();
            }
        });
        builder.show();
    }

    /**
     * 拒绝
     */
    @OnPermissionDenied(Manifest.permission.READ_EXTERNAL_STORAGE)
    public void onCameraDenied() {
        Log.e(TAG, "onCameraDenied: ");
        finish();
    }

    @OnNeverAskAgain(Manifest.permission.READ_EXTERNAL_STORAGE)
    public void onCameraNeverAskAgain() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("没有权限无法发动态，请到设置开启权限");

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        builder.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
      PublishActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
